<script>
import { reactive, watch, nextTick } from "vue";
import { getDicMap, getColdCompany } from "@/utils/storage";
import { useTzRouter } from "@/vhooks/useTzRouter";
import Taro from "@tarojs/taro";
import { queryTrailerApi } from "./api";

export default {
  name: "AddTray",
  components: {},
  setup() {
    const { route, navigateBack } = useTzRouter();
    const dicMap = getDicMap();

    const state = reactive({
      showT: true,
      isEdit: false,
      // 托架表单
      formModel: {
        trailerCode: "",
        trailerTypeCode: "",
        trailerWeight: "",
        isEnable: false,
      },
    });

    // 回填数据
    if (route.query.trayInfo) {
      Taro.setNavigationBarTitle({ title: "编辑托架信息" });
      (() => {
        state.isEdit = true;
        const tempTrayInfo = JSON.parse(route.query.trayInfo);
        if (typeof tempTrayInfo.isEnable === "string") {
          // 带发电机 checkbox  01 勾选  02 不勾选
          tempTrayInfo.isEnable = tempTrayInfo.isEnable === "01" ? true : false;
        }

        const { showT, trailerCode } = tempTrayInfo;

        if (showT || /T$/.test(tempTrayInfo.trailerCode)) {
          tempTrayInfo.trailerCode = trailerCode.substr(
            0,
            trailerCode.length - 1
          );
          state.showT = true;
        } else {
          state.showT = false;
        }
        state.formModel = { ...state.formModel, ...tempTrayInfo };
      })();
    }

    const removeTray = () => {
      Taro.showModal({
        content: "确定删除该条记录吗?",
        confirmText: "确定",
        cancelText: "取消",
      }).then((res) => {
        if (res.confirm) {
          navigateBack({
            delta: 1,
            event: {
              type: "deleteTray", // 删除托架数据
            },
          });
        }
      });
    };

    const handleChange = (e) => {
      console.log("托架规格切换", e);
    };

    /**
     * 是否为空字符串
     */
    const isEmpty = (str) => {
      if (typeof str === "number") {
        str = str.toString();
      }
      return (
        str === null || str === undefined || str.trim() === "" || str === "null"
      );
    };

    const isTrailerCode = (str) => {
      //1017 舱单确报时托架号最后一位默认填写字母T---S
      // if (state.showT && str.length > 5) {
      //   return true;
      // }
      //---E
      const patrn = /^[A-Z0-9]{1,6}$/;
      return !patrn.exec(str);
    };

    // 托架重量
    const isNumberLength = (num) => {
      const patrn = /^(?!0)[0-9]{4,5}$/;
      return !patrn.exec(num);
    };

    const isGeneratorWeight = (num) => {
      const patrn = /^(?!0)[0-9]{1,5}/;
      return !patrn.exec(num);
    };

    const checkFormData = (data) => {
      const {
        trailerTypeCode,
        trailerWeight,
        isEnable,
        generatorWeight,
      } = data;
      let trailerCode = data.trailerCode;
      if (state.showT) {
        trailerCode += "T";
      }
      try {
        // 托架号
        if (isEmpty(trailerCode)) {
          throw new Error("请输入托架号");
        }
        if (isTrailerCode(trailerCode)) {
          throw new Error("托架号是由大写字母和数字组成的1到6位字符");
        }
        // 托架规格
        if (isEmpty(trailerTypeCode)) {
          throw new Error("托架规格不能为空");
        }
        // 托架重量
        if (isEmpty(trailerWeight)) {
          throw new Error("托架重量不能为空");
        }
        if (isNumberLength(trailerWeight)) {
          throw new Error("托架重量只能录入4到5位数字");
        }
        if (isEnable && getColdCompany().isColdCompany === "01") {
          if (isEmpty(generatorWeight)) {
            throw new Error("发电机重量不能为空");
          }
          if (isGeneratorWeight(generatorWeight)) {
            throw new Error("发电机重量只能输入1~5位有效正实数");
          }
        }
        return true;
      } catch (err) {
        Taro.showToast({
          title: err.message,
          icon: "none",
          duration: 2000,
        });
        return false;
      }
    };

    const handleSave = async () => {
      // 保存校验
      if (!checkFormData(state.formModel)) return;
      // 校验托架号
      let trailerCode = state.formModel.trailerCode;
      state.showT && (trailerCode += "T");
      const lastTwo = trailerCode.substring(trailerCode.length - 2);
      if (lastTwo === "TT") {
        //托架号最后两位为TT时，提示用户：你录入的车架号为[xxxx]，确认要保存吗？确认后允许保存。
        const confirmTrailerCode = await Taro.showModal({
          content: "你录入的车架号为[" + trailerCode + "]，确认要保存吗？",
          confirmText: "是",
          cancelText: "否",
        });
        // 取消保存
        if (!confirmTrailerCode.confirm) return;
      }

      // 校验架重
      const trailerWeight = state.formModel.trailerWeight;
      if (trailerWeight.length > 4) {
        const confirmTraiWeigth = await Taro.showModal({
          content: "架重超过4位，是否继续?",
          confirmText: "是",
          cancelText: "否",
        });
        if (!confirmTraiWeigth.confirm) return;
      }

      // 校验发电机重量
      const { isEnable, generatorWeight } = state.formModel;
      const {
        generatorWeightMin: minWeight,
        generatorWeightMax: maxWeight,
      } = getColdCompany();
      if (
        isEnable &&
        (minWeight > generatorWeight || generatorWeight > maxWeight)
      ) {
        Taro.showToast({
          title: `发电机重量(KG)的范围是${minWeight}~${maxWeight}`,
          icon: "none",
          duration: 2000,
        });
        return false;
      }

      if (state.showT) {
        state.formModel.trailerCode += "T";
        state.formModel.showT = true; // 返回编辑状态下使用
      } else {
        state.formModel.showT = false;
      }
      navigateBack({
        delta: 1,
        event: {
          type: "trayAddBack", //事件类型 ，可以自己任意定义
          // REVIEW: 这里如果不做拷贝，数据传过去后会被改变，例如托架号 999999T 会变成 999999
          // 应该是 watch state.formModel 里面做了处理
          data: JSON.parse(JSON.stringify(state.formModel)), //回退的数据
        },
      });
    };
    const handleCheckT = () => {
      state.showT = !state.showT;
    };
    const handleCheckWeight = (e) => {
      if (!e.detail.value) {
        state.formModel.generatorWeight = "";
      }
      state.isEnable = !state.isEnable;
    };

    const getByTrailerCode = (code) => {
      // 查询托架信息，自动填充表单
      queryTrailerApi({ trailerCode: code }).then((res) => {
        if (res.data) {
          const { trailerTypeCode, trailerWeight } = res.data;
          state.formModel.trailerTypeCode = trailerTypeCode;
          state.formModel.trailerWeight = trailerWeight;
        }
      });
    };

    // 更改后缀 T，查询托架信息
    watch(
      () => state.showT,
      (val) => {
        let trailerCode = state.formModel.trailerCode;
        if (val) {
          trailerCode += "T";
        }
        if (trailerCode.length > 3 && !dicMap.userType.isPersonal) {
          getByTrailerCode(trailerCode);
        }
      }
    );

    return () => {
      return (
        <tz-view class="add-tray">
          <tz-view class="form-content">
            <tz-view class="base-info">
              <tz-cell title="托架号" border>
                <tz-input
                  type="text"
                  placeholder="请输入托架号"
                  v-model={state.formModel.trailerCode}
                  maxlength="6"
                  clearable
                  rules={(val) => {
                    const value = val?.match(/[a-zA-Z0-9]{1,6}/g)?.[0] || "";
                    if (value.length > 3 && !dicMap.userType.isPersonal) {
                      let searchVal = value;
                      if (state.showT) {
                        searchVal += "T";
                      }
                      getByTrailerCode(searchVal);
                    }
                    return value.toUpperCase();
                  }}
                />
                <text class="letter-t" v-show={state.showT}>
                  T
                </text>
                <tz-view class="suffix-t-switch">
                  <tz-switch type="checkbox" v-model={state.showT}></tz-switch>
                  <tz-text onClick={handleCheckT}>T字结尾</tz-text>
                </tz-view>
              </tz-cell>

              <tz-cell title="托架规格" border>
                <tz-picker
                  v-model={state.formModel.trailerTypeCode}
                  mode="selector"
                  range={dicMap.trailerTypeCodeList}
                  rangeKey="para_name"
                  valueKey="para_value"
                  onChange={(e) => handleChange(e)}
                ></tz-picker>
              </tz-cell>
              <tz-cell title="架重(KG)" border>
                <tz-input
                  v-model={state.formModel.trailerWeight}
                  type="number"
                  placeholder="请输入架重(KG)"
                  maxlength="5"
                  clearable
                ></tz-input>
              </tz-cell>
            </tz-view>
            {getColdCompany().isColdCompany === "01" && (
              <tz-view>
                <tz-cell title="带发电机" border>
                  <tz-switch
                    type="checkbox"
                    v-model={state.formModel.isEnable}
                    onChange={handleCheckWeight}
                  ></tz-switch>
                </tz-cell>
                <tz-cell title="发电机重量(KG)" border>
                  <tz-input
                    v-model={state.formModel.generatorWeight}
                    type="number"
                    placeholder="请输入发电机重量(KG)"
                    maxlength="5"
                    disabled={!state.formModel.isEnable}
                    clearable
                  ></tz-input>
                </tz-cell>
              </tz-view>
            )}
          </tz-view>
          <tz-view class="btn-block">
            {state.isEdit && (
              <tz-button
                class="del-btn"
                type="danger"
                onClick={() => removeTray()}
              >
                删除
              </tz-button>
            )}
            <tz-button
              class="submit-btn"
              type="primary"
              onClick={() => handleSave()}
            >
              保存
            </tz-button>
          </tz-view>
        </tz-view>
      );
    };
  },
};
</script>

<style lang="scss">
.add-tray {
  display: flex;
  flex-direction: column;
  align-items: center;
  .form-content {
    width: 100%;
    background: #fff;
    border-top: 1px solid #d9d9d9;
    padding: 0 15px;
    .base-info {
      .tz-cell-label {
        width: 80px;
      }
      .tz-cell-value {
        .letter-t {
          // margin-right: 20px;
        }
        .suffix-t-switch {
          width: 100%;
          display: flex;
          justify-content: flex-end;
          align-items: center;
          .tz-switch {
            display: inline-flex;
          }
        }
      }
    }
  }
  .btn-block {
    width: 345px;
    margin-top: 20px;
    display: flex;
    justify-content: center;
    .del-btn {
      flex: 1;
      margin-right: 20px;
    }
    .submit-btn {
      flex: 1;
    }
  }
}
</style>
